import tkinter as tk
import sqlite3
from tkinter import ttk
from environment_page import EnvironmentPage
from image_page import ImagePage

class MainApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("电缆井监测系统")
        self.geometry("800x600")
        
        # 创建导航框架
        nav_frame = ttk.Frame(self)
        nav_frame.pack(side="top", fill="x", padx=10, pady=10)
        
        # 创建页面容器
        self.container = ttk.Frame(self)
        self.container.pack(fill="both", expand=True)
        
        # 初始化页面
        self.pages = {}
        for PageClass in (HomePage, EnvironmentPage, ImagePage):
            page_name = PageClass.__name__
            page = PageClass(parent=self.container, controller=self)
            self.pages[page_name] = page
            page.grid(row=0, column=0, sticky="nsew")
        
        # 显示首页
        self.show_page("HomePage")
        
        # 创建导航按钮
        ttk.Button(nav_frame, text="主页", command=lambda: self.show_page("HomePage")).pack(side="left")
        ttk.Button(nav_frame, text="环境监测", command=lambda: self.show_page("EnvironmentPage")).pack(side="left", padx=10)
        ttk.Button(nav_frame, text="图片查看", command=lambda: self.show_page("ImagePage")).pack(side="left")
        ttk.Button(nav_frame, text="停止系统", command=self.destroy).pack(side="right")
    
    def show_page(self, page_name):
        page = self.pages[page_name]
        page.tkraise()
        page.update_data()  # 更新页面数据

class HomePage(ttk.Frame):
    def __init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller
        
        title_label = ttk.Label(self, text="电缆井的远程监测系统", font=("微软雅黑", 24, "bold"))
        title_label.pack(pady=50)
        
        status_frame = ttk.Frame(self)
        status_frame.pack(pady=20)
        
        self.last_update = ttk.Label(status_frame, text="最后更新: --")
        self.last_update.pack(side="left", padx=20)
        
    def update_data(self):
        try:
            conn = sqlite3.connect('sensor_data.db')
            c = conn.cursor()
            c.execute("SELECT MAX(timestamp) FROM sensor_data")
            last_ts = c.fetchone()[0]
            self.last_update.config(text=f"最后更新: {last_ts if last_ts else '无记录'}")
        except sqlite3.Error as e:
            print(f"数据库错误: {e}")
            self.last_update.config(text="最后更新: 数据库错误")
        finally:
            if 'conn' in locals():
                conn.close()

if __name__ == "__main__":
    app = MainApp()
    app.mainloop()